import fs from "fs";
import {saveFile} from "../utils/file.js";
import {video} from "../model/video.js";
import sequelize from "../db.js";
import User from "../model/user.js";

export async function saveVideo(req){
    const path = `D:\\Project\\Campube\\campubeFile\\`
    const {files, fields} = await saveFile(path, req)
    const video = files.videoFile
    const cover = files.videoCover
    const videoTempFilePath = video[0].filepath;
    const videoTargetFilePath = `D:\\Project\\Campube\\campubeFile\\video\\${fields.title[0]}.mp4`
    const coverTempFilePath = cover[0].filepath;
    const coverTargetFilePath = `D:\\Project\\Campube\\campubeFile\\videoCover\\${fields.title[0]}.jpg`
    fields.videoPath = videoTargetFilePath
    fields.coverPath = coverTargetFilePath
    fs.renameSync(videoTempFilePath, videoTargetFilePath)
    fs.renameSync(coverTempFilePath, coverTargetFilePath)

    return {
        files,
        fields
    }
}

// export async function saveVideoCover(req){
//     const path = `D:\\Project\\Campube\\campubeFile\\`
//     const files = await saveFile(path, req)
//     const cover = files.videoCover
//     const tempFilePath = cover[0].filepath;
//     const targetFilePath = "D:\\Project\\Campube\\campubeFile\\videoCover\\a.png"
//     fs.renameSync(tempFilePath, targetFilePath)
// }

export async function uploadVideoData(videoData){
    const result = await video.create({
        video_title: videoData.title,
        video_description: videoData.description,
        video_type: videoData.type,
        video_tag: videoData.tag,
        video_file: videoData.videoPath,
        video_cover: videoData.coverPath,
        video_creator: videoData.creator
    })

    return result
}

export async function getVideoData(){
    let videoCount = 4

    const result = await video.findAll({
        order: sequelize.random(),
        limit: videoCount,
        include: User
    })

    return result
}

export async function getVideoDataById(videoId){
    const result = await video.findAll({
        where: {
            video_id: videoId
        }
    })

    return result
}
